﻿using System;
using System.Collections.Generic;
using System.Text;

namespace News.CYT369.Com.DAL
{
    public class RedisService
    {
        protected static readonly RedisService m_Instance = new RedisService();

        /// <summary>
        /// 连接redis数据库
        /// </summary>
        /// <returns></returns>
        private StackExchange.Redis.ConnectionMultiplexer GetConnection()
        {
            var connection = StackExchange.Redis.ConnectionMultiplexer.Connect(News.CYT369.Com.Domains.SystemSettingService.Instance.RedisConnection);

            return connection;
        }

        /// <summary>
        /// 单实例
        /// </summary>
        public static RedisService Instance
        {
            get { return m_Instance; }
        }

        public bool SetSysUserCache(News.CYT369.Com.Domains.Identity.SysUser sysUser)
        {
            using (var connection = GetConnection())
            {
                var db = connection.GetDatabase(1);
                var r = db.StringSet(sysUser.Id.ToString(), System.Text.Json.JsonSerializer.Serialize(sysUser), new TimeSpan(24, 0, 0));

                return r;
            }
        }

        public News.CYT369.Com.Domains.Identity.SysUser GetSysUserCache(string userId)
        {
            using (var connection = GetConnection())
            {
                var db = connection.GetDatabase(1);
                var json = db.StringGet(userId);
                if (!string.IsNullOrEmpty(json))
                {
                    var r = System.Text.Json.JsonSerializer.Deserialize<News.CYT369.Com.Domains.Identity.SysUser>(json);

                    return r;
                }
            }

            return null;
        }


    }
}
